/**
 * 持久化工具 - 基于Preferences
 */
import { preferences } from '@kit.ArkData'
import { BusinessError } from '@kit.BasicServicesKit'
import { common } from '@kit.AbilityKit'

const STORE_NAME = 'app_store'
let dataPreferences: preferences.Preferences | null = null

/**
 * 初始化Preferences
 */
async function getPreferences(context: common.Context): Promise<preferences.Preferences> {
  if (dataPreferences) {
    return dataPreferences
  }
  
  try {
    const options: preferences.Options = { name: STORE_NAME }
    dataPreferences = await preferences.getPreferences(context, options)
    return dataPreferences
  } catch (err) {
    const error = err as BusinessError
    console.error(`获取Preferences失败, code: ${error.code}, message: ${error.message}`)
    throw error
  }
}

/**
 * 存储工具类
 */
export class PersistUtil {
  private static context: common.Context | null = null
  
  /**
   * 初始化context（应用启动时调用）
   */
  static init(context: common.Context) {
    this.context = context
  }
  
  /**
   * 保存数据
   */
  static async set(key: string, value: any): Promise<void> {
    if (!this.context) {
      console.warn('PersistUtil未初始化，无法保存数据')
      return
    }
    
    try {
      const prefs = await getPreferences(this.context)
      const jsonStr = JSON.stringify(value)
      await prefs.put(key, jsonStr)
      await prefs.flush()
    } catch (err) {
      const error = err as BusinessError
      console.error(`保存数据失败, key: ${key}, error: ${error.message}`)
    }
  }
  
  /**
   * 获取数据
   */
  static async get<T>(key: string, defaultValue: T): Promise<T> {
    if (!this.context) {
      console.warn('PersistUtil未初始化，返回默认值')
      return defaultValue
    }
    
    try {
      const prefs = await getPreferences(this.context)
      const jsonStr = await prefs.get(key, '') as string
      
      if (!jsonStr) {
        return defaultValue
      }
      
      return JSON.parse(jsonStr) as T
    } catch (err) {
      const error = err as BusinessError
      console.error(`获取数据失败, key: ${key}, error: ${error.message}`)
      return defaultValue
    }
  }
  
  /**
   * 删除数据
   */
  static async remove(key: string): Promise<void> {
    if (!this.context) {
      console.warn('PersistUtil未初始化')
      return
    }
    
    try {
      const prefs = await getPreferences(this.context)
      await prefs.delete(key)
      await prefs.flush()
    } catch (err) {
      const error = err as BusinessError
      console.error(`删除数据失败, key: ${key}, error: ${error.message}`)
    }
  }
  
  /**
   * 清空所有数据
   */
  static async clear(): Promise<void> {
    if (!this.context) {
      console.warn('PersistUtil未初始化')
      return
    }
    
    try {
      const prefs = await getPreferences(this.context)
      await prefs.clear()
      await prefs.flush()
    } catch (err) {
      const error = err as BusinessError
      console.error(`清空数据失败, error: ${error.message}`)
    }
  }
  
  /**
   * 检查key是否存在
   */
  static async has(key: string): Promise<boolean> {
    if (!this.context) {
      return false
    }
    
    try {
      const prefs = await getPreferences(this.context)
      return await prefs.has(key)
    } catch (err) {
      const error = err as BusinessError
      console.error(`检查key失败, key: ${key}, error: ${error.message}`)
      return false
    }
  }
}

